<template>
  <a-card :bordered="false">
    <a-modal
      :title="modalTitle"
      width="20%"
      :maskClosable="false"
      :visible="visible"
      :confirmLoading="confirmLoading"
      @cancel="handleCancel"
      cancelText="关闭"
    >
      <template slot="footer">
        <a-button key="back" @click="handleReject()">
          不通过
        </a-button>
        <a-button key="submit" type="primary" :loading="loading" @click="handleAdopt()">
          通过
        </a-button>
      </template>
      请填写审批意见：
      <a-input v-model="flowOpinion" type="textarea" />
    </a-modal>

    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :md="6" :sm="8">
            <a-form-item label="业务摘要">
              <a-input placeholder="请输入业务摘要" v-model="queryParam.summary"></a-input>
            </a-form-item>
          </a-col>
          <a-col :md="6" :sm="8" >
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
            </span>
          </a-col>

        </a-row>
      </a-form>
    </div>
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="submitMany" type="primary" icon="check">批量处理</a-button>
    </div>

    <!-- table区域-begin -->
    <div>
      <div v-if="selectedRowKeys.length > 0" class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        bordered
        rowKey="id"
        :columns="columns"
        :scroll="{ x: 1500 }"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        @change="handleTableChange">
        <!-- 字符串超长截取省略号显示-->
        <span slot="businessKey" slot-scope="text,record"><a-tooltip><template slot="title">{{customRender(record)}}</template>{{customRender(record)}}</a-tooltip></span>
        <span slot="action" slot-scope="text, record" >
          <a @click="toDeal(record)">办理</a>
          <a-popconfirm title="确定清理数据吗?" v-if="currentUsername == '管理员'" @confirm="() => cleanProcessData(record)">
            <a-divider type="vertical"/>
            <a>清理数据</a>
          </a-popconfirm>
        </span>
      </a-table>
    </div>
    <!-- table区域-end -->

    <!-- 表单区域 -->
    <examine-modal ref="modalForm" @ok="modalFormOk"></examine-modal>
    <history-list ref="modalList" @ok="modalFormOk"></history-list>
    <task-deal-modal :businessKey="businessKey" :taskId="taskId" :pageName="pageUrl" :flow="flow"
                      :editUrl="editUrl" :innerpage="innerpage" :internalUrl="internalUrl" :customform="customform"
                     ref="taskDealModal" @ok="modalFormOk"></task-deal-modal>
  </a-card>
</template>

<script>
  import ExamineModal from './modules/ExamineModal'
  import HistoryList from './modules/HistoryList'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import { getAction,deleteAction,putAction,postAction,httpAction} from '@/api/manage'
  import TaskDealModal from '../../components/page/TaskDealModal'
  import moment from "moment"
  import JEllipsis from "@/components/jeecg/JEllipsis";
  import Vue from 'vue'
  import store from '@/store/'

  export default {
    name: "TodoList",
    mixins:[JeecgListMixin],
    components: {
      ExamineModal,
      HistoryList,
      TaskDealModal,
      JEllipsis
    },
    data () {
      return {
        description: '我的待办页面',
        modalTitle: '审批',
        visible: false,
        confirmLoading: false,
        // 表头
        columns: [
           {
            title: '业务摘要',
            align:"left",
            dataIndex: 'summary',
             // width:300,
             scopedSlots: { customRender: 'businessKey' },
             ellipsis:true,
          },
		      {
            title: '待办任务名称',
            align:"center",
            dataIndex: 'name',
            width:180
           },
           {
            title: '部室名称',
            align:"center",
            dataIndex: 'dept',
            width:250
           },
          {
            title: '申请人',
            align:"center",
            dataIndex: 'startUserId',
            width:130
          },
          {
            title: '处理人',
            align:"center",
            dataIndex: 'assigneeName',
            width:230,
            ellipsis:true
          },
          {
            title: '处理时间',
            align:"center",
            dataIndex: 'createTime',
            customRender: (text, row, index) => {
              if (text != ''){
                return moment(text).format("YYYY-MM-DD HH:mm");
              }
            },
            sorter: true,
            width:180
          },

          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            width:180,
            scopedSlots: { customRender: 'action' },
            fixed: "right"
          }
        ],
		url: {
          list: "/act/task/todo",
          delete: "/act/model/delete",
          deleteBatch: "/act/model/deleteBatch",
          exportXlsUrl: "model/model/exportXls",
          importExcelUrl: "model/model/importExcel",
      //校验绩效功能是否开放接口
      check:'/reimb/expenditureReimbInfo/check',
      getReimbIdByVirtualId:'/reimb/expenditureSubsistVirtual/getReimbIdByVirtualId',
       },
        addModel:true,
        modelSrc:'',
        flowOpinion:'',
        pageUrl:'',
        pId:'',
        businessKey:"",
        taskId:"",
        tableId:"",
        title:"",
        editUrl:"",
        innerpage:"",
        internalUrl:"",
        taskIds:"",
        customform: "",
        currentUsername:"",
        flow:1,
    }
  },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    created(){
      let user = Vue.ls.get('Login_Userinfo')
      this.currentUsername = user.realname
    },

    methods: {
      /**
       * @author pqz
       * @description 校验绩效功能是否开放
       */
      check(){
        return getAction(this.url.check, {}).then((res) => {
          return '1' == res.message
        })
      },
      handleAdopt(){
        this.submit(this.taskIds,1,this.flowOpinion);
        this.visible = false
      },
      handleCancel(){
        this.visible = false
      },
      handleReject(){
        /**
         * @author 于晓洋
         * @description 点击不通过时验证审批意见是否填写
         */
        if(this.flowOpinion){
          this.submit(this.taskIds,0,this.flowOpinion);
          this.visible = false ;
        }else{
          this.$message.warn('请填写审批意见');
          return false;
        }
      },
      customRender(record){
          let summary = record.summary;
          var m = summary.match( new RegExp('title":"'+'(.*?)'+'"') );
          return m ? m[ 1 ] : '';
      },
      Ellipsis(record){
        if(record==undefined || record==null || record==''){
          record=" "
        }
        if(record.length > 17){
          return record.substring(0,17)+"..."

        }else {
          return record
        }

      },
      submitMany() {
        if (this.selectionRows.length == 0) {
          this.$message.warning('请选择一条数据！')
          return false
        }
        console.log('this.selectionRows',this.selectionRows)
        for(let i=0;i<this.selectionRows.length;i++){
          if(this.selectionRows[i].editUrl != null && this.selectionRows[i].editUrl != undefined && this.selectionRows[i].editUrl.indexOf('innerpage') != -1){
            this.$message.warning('当前选中数据需要进行修改，请点击办理进行处理');
            return false;
          }
        }
        let idArr = ''

        this.selectionRows.forEach(val => {
          idArr += val.id + ","
        })
        let taskIds = idArr.substring(0, idArr.length - 1);
        this.taskIds = taskIds
        let that = this;
        this.flowOpinion = ""
        this.visible = true
      },

      submit(taskIds,flag,flowOpinion){
        let flowOpinionFinal = '审批通过'
        //如果点击通过默认没填意见，则使用审批通过提示语，若传了值，则使用实际的意见
        if(flowOpinion){
          flowOpinionFinal = flowOpinion
        }
        httpAction("/handle/task/completeMany/"+taskIds+"/"+flag+'?flowOpinion='+flowOpinionFinal,{},'post').then((res)=>{
          if(res.success){
            this.$message.success(res.message);
            this.loadData();
            this.onClearSelected();
          }else{
            this.$message.warning(res.message);
          }
        }).finally(() => {
          this.confirmLoading = false;
          this.close();
        })
      },


      editModel(row){
        let url =window._CONFIG['domianURL']+'/modeler.html?modelId='+row.id;
        window.open(url);
      },
      deployModel(row){
        const that = this;

        this.$confirm({
          title: "提示",
          content: "请确认点击了左上角的保存按钮?",
          onOk: function () {
            that.loading = true;
            getAction("/act/model/deploy/",{id:row.id}).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
              }else{
                that.$message.warning(res.message)
              }
            });
          }
        });


      },
      showApprove(record,flag){
        this.$refs.modalForm.title = "审批";
        this.$refs.modalForm.departDisabled = true;
        this.$refs.modalForm.disableSubmit = false;
        this.$refs.modalForm.edit(record,flag);
      },
      showHistory(row){
        this.$refs.modalList.init(row.businessKey);
        this.$refs.modalList.title = "审批历史";
        this.$refs.modalList.disableSubmit = false;
      },
      toDetail(record){
        this.$router.push(record.url);
      },
      async toDeal(record){
        this.$refs.taskDealModal.isOpenPlanPer = false
        this.$refs.taskDealModal.isOpenReimbPer = false
        //校验是否配置了绩效开关
        let isCheckPer =await this.check().then((res)=>{
          return res
        })
        this.businessKey = record.businessKey;
        if(this.businessKey.indexOf("expenditure_subsist_virtual.expenditure_subsist_virtual")!==-1){
          //预付款子流程，需要根据tableId获取报销主数据id
          await getAction(this.url.getReimbIdByVirtualId,{virtualId:record.tableId}).then(res=>{
            if(res.success){
              record.tableId=res.message
            }
          })
        }
        this.taskId = record.id;
        this.editUrl = record.editUrl;
        this.internalUrl = record.internalUrl;

        this.flow = record.flow

        if(record.editUrl==null||record.editUrl==''||record.editUrl==undefined){
          //FormKey不存在的时候处理页面显示详情页面
          this.pageUrl = record.url;
          this.innerpage =null //为空 清空上次的值
        }else if(record.editUrl.indexOf("innerpage")!=-1){
          //FormKey存在而且包含内嵌页的时候处理页面显示详情页+显示详情页中的内嵌页
          this.innerpage = record.editUrl.split(':')[1];
          //如果innerpage是编辑所有信息，替换为编辑页
          if(this.innerpage && this.innerpage.indexOf('editAll')!==-1){
            await getAction("/handle/getVariables/"+record.procInstId).then(res=>{
              if(res.success && res.result && res.result.editUrl){
                this.pageUrl = res.result.editUrl
              }
            })
          }else{
            this.pageUrl = record.url
          }
        }else{
          //FormKey存在而且不包含内嵌页的时候处理页面调用FormKey填写的页面
          this.pageUrl = record.editUrl;
        }
        console.log(record)
        if(record.customform.indexOf("customform")!=-1 || record.customform.indexOf("dynamic")!=-1){
          //FormKey存在而且包含内嵌页的时候处理页面显示详情页+显示详情页中的内嵌页
          this.customform = record.customform;
        }
        this.$refs.taskDealModal.width = '90%';
        if(record.businessKey){
          if(record.businessKey.split('.')[0] == 'expenditure_plan'){
            // this.$refs.taskDealModal.onlyViewPrint = true;
            record.title=record.title.replace('详细','·事前申请')
            //校验是否配置了绩效开关
            this.$refs.taskDealModal.isOpenPlanPer = isCheckPer
          }else if(record.businessKey.split('.')[0] == 'expenditure_reimb_info'){
            // this.$refs.taskDealModal.onlyViewPrint = true;
            record.title=record.title.replace('详细','·事后报销')
            //校验是否配置了绩效开关
            this.$refs.taskDealModal.isOpenReimbPer = isCheckPer
          }else{
            // this.$refs.taskDealModal.onlyViewPrint = false;
          }
        }
        console.log(this.pageUrl,'---this. ---')
        this.$refs.taskDealModal.expendType = record.expendType;
        this.$refs.taskDealModal.initData(record.tableId,(record.startUserId?(record.startUserId +'·'):'')+record.title,record,"do");
        this.$refs.taskDealModal.disableSubmit = false;
      },
      cleanProcessData(row){
        const that = this;
        that.loading = true;
        //alert(row.businessKey);
        postAction("/handle/cleanProcessData/"+row.businessKey,{}).then((res)=>{
          if(res.success){

            that.$message.success(res.message);
            this.loadData(1);
          }else{
            that.$message.warning(res.message)
          }
        }).finally(() => {
          that.loading = false;
        });
      },


    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>